<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="./index.css">
</head>
<body>
  <div class="websocket">
    773914
    <div class="receive">
      <p>服务端返回的消息</p>
      <div id="receive-box"></div>
    </div>
    <div class="send">
      <textarea type="text" id="msg-need-send"></textarea>
      <p>
        <button id="send-btn">点击发消息给服务端</button>
      </p>
    </div>
    <button id="exit">关闭连接</button>
  </div>
</body>
</html>
<script>
  const msgBox = document.getElementById('msg-need-send')
const sendBtn = document.getElementById('send-btn')
const exit = document.getElementById('exit')
const receiveBox = document.getElementById('receive-box')

const ws = new WebSocket('ws://127.0.0.1:8080/websocket/test?userID=773914')
ws.onopen = e => {
  console.log(`WebSocket 连接状态： ${ws.readyState}`)
}

ws.onmessage = data => {
  receiveBox.innerHTML += `<p>${data.data}</p>`
  receiveBox.scrollTo({
    top: receiveBox.scrollHeight,
    behavior: "smooth"
  })
}

ws.onclose = data => {
  console.log('WebSocket连接已关闭')
  console.log(data);
}


sendBtn.onclick = () => {
  ws.send(JSON.stringify({
    fromId: "773914",
    payload: msgBox.value
  }))
}
exit.onclick = () => {
  ws.close()
}
</script>